package com.example.w.common.realm;

import com.example.w.common.pojo.User;
import com.example.w.common.util.ApplicationContextUtils;
import com.example.w.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;


public class CustomerRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("获取授权信息");
        //获取用户名
        String principal = (String) principals.getPrimaryPrincipal();
        //获取userService
        UserService userService = (UserService) ApplicationContextUtils.getBean("userServiceImpl");
        //查询用户角色
        User user = userService.selectRolesByUsername(principal);
        if (!CollectionUtils.isEmpty(user.getRoles())) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            user.getRoles().forEach(role -> {
                info.addRole(role.getRole());
            });
            return info;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户名
        String principal = (String) token.getPrincipal();
        //获取userService对象
        UserService userService = (UserService) ApplicationContextUtils.getBean("userServiceImpl");
        //获取用户实例
        User user = userService.selectUserByUsername(principal);
        //返回info
        if (!ObjectUtils.isEmpty(user)) {
            SimpleAuthenticationInfo info =
                    new SimpleAuthenticationInfo(
                            principal,
                            user.getPassword(),
                            ByteSource.Util.bytes(user.getSalt()),
                            getName());
            return info;
        }

        return null;
    }
}
